#!/usr/bin/env node

/**
 * 测试帮派系统功能
 * 包括创建帮派、查询帮派信息、查询成员、解散帮派、申请加入等功能
 */

const WebSocket = require('ws');

class FactionSystemTester {
    constructor() {
        this.ws = null;
        this.testResults = [];
    }

    async connect() {
        console.log('🔌 连接到WebSocket服务器...');

        return new Promise((resolve, reject) => {
            this.ws = new WebSocket('ws://localhost:3000/user-service/websocket');

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接失败:', error.message);
                reject(error);
            });
        });
    }

    async login() {
        console.log('\n🔐 步骤1: 用户登录...');

        const loginMessage = {
            c: 0,
            d: {
                username: "testuser",
                password: "testpass"
            }
        };

        this.ws.send(JSON.stringify(loginMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 登录超时，继续测试...');
                resolve();
            }, 5000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 登录响应:', JSON.stringify(response, null, 2));
                    resolve();
                } catch (error) {
                    console.log('⚠️ 登录响应解析失败，继续测试...');
                    resolve();
                }
            });
        });
    }

    async selectCharacter() {
        console.log('\n👤 步骤2: 选择角色...');

        const selectMessage = {
            c: 3,
            d: {
                roleId: 1
            }
        };

        this.ws.send(JSON.stringify(selectMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 角色选择超时，继续测试...');
                resolve();
            }, 5000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 角色选择响应:', JSON.stringify(response, null, 2));
                    resolve();
                } catch (error) {
                    console.log('⚠️ 角色选择响应解析失败，继续测试...');
                    resolve();
                }
            });
        });
    }

    async testCreateFaction() {
        console.log('\n🏛️ 步骤3: 测试创建帮派...');

        const createMessage = {
            c: 1236,
            d: {
                type: 4, // 帮
                name: "测试帮派",
                desc: "这是一个测试帮派"
            }
        };

        console.log('📤 发送请求:', JSON.stringify(createMessage, null, 2));
        this.ws.send(JSON.stringify(createMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 创建帮派超时');
                this.addTestResult('创建帮派测试', false, '创建超时');
                resolve();
            }, 10000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 创建响应:', JSON.stringify(response, null, 2));

                    // 验证响应格式
                    if (response.act_id === 260 && response.code === 0) {
                        console.log('✅ 帮派创建成功');
                        this.addTestResult('创建帮派测试', true, '创建成功');
                    } else {
                        console.log('❌ 帮派创建失败:', response.msg || '未知错误');
                        this.addTestResult('创建帮派测试', false, response.msg || '创建失败');
                    }
                    resolve();
                } catch (error) {
                    console.log('❌ 响应解析失败:', error.message);
                    this.addTestResult('创建帮派测试', false, '响应解析失败');
                    resolve();
                }
            });
        });
    }

    async testFactionInfoQuery() {
        console.log('\n📋 步骤4: 测试帮派信息查询...');

        const queryMessage = {
            c: 1126
        };

        console.log('📤 发送请求:', JSON.stringify(queryMessage, null, 2));
        this.ws.send(JSON.stringify(queryMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 帮派信息查询超时');
                this.addTestResult('帮派信息查询测试', false, '查询超时');
                resolve();
            }, 10000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 查询响应:', JSON.stringify(response, null, 2));

                    // 验证响应格式
                    if (response.act_id === 1126) {
                        if (response.code === 0 && response.data) {
                            console.log('✅ 帮派信息查询成功');
                            console.log('📋 帮派信息:');
                            console.log(`   名称: ${response.data.name}`);
                            console.log(`   等级: ${response.data.lvl}`);
                            console.log(`   成员数: ${response.data.mem}/${response.data.maxSum}`);
                            console.log(`   帮主: ${response.data.lead}`);
                            this.addTestResult('帮派信息查询测试', true, '查询成功');
                        } else {
                            console.log('❌ 帮派信息查询失败:', response.msg || '未知错误');
                            this.addTestResult('帮派信息查询测试', false, response.msg || '查询失败');
                        }
                    } else {
                        console.log('⚠️ 响应格式不符合预期');
                        this.addTestResult('帮派信息查询测试', false, '响应格式错误');
                    }
                    resolve();
                } catch (error) {
                    console.log('❌ 响应解析失败:', error.message);
                    this.addTestResult('帮派信息查询测试', false, '响应解析失败');
                    resolve();
                }
            });
        });
    }

    async testFactionMembersQuery() {
        console.log('\n👥 步骤5: 测试帮派成员查询...');

        const queryMessage = {
            c: 1218,
            d: {
                id: 1, // 假设帮派ID为1
                pageNum: 0
            }
        };

        console.log('📤 发送请求:', JSON.stringify(queryMessage, null, 2));
        this.ws.send(JSON.stringify(queryMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 帮派成员查询超时');
                this.addTestResult('帮派成员查询测试', false, '查询超时');
                resolve();
            }, 10000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 查询响应:', JSON.stringify(response, null, 2));

                    // 验证响应格式
                    if (response.act_id === 1218) {
                        if (response.code === 0 && Array.isArray(response.list)) {
                            console.log('✅ 帮派成员查询成功');
                            console.log('👥 成员列表:');
                            response.list.forEach(member => {
                                console.log(`   ${member.n} (${member.t}) - 角色: ${member.o}`);
                            });
                            this.addTestResult('帮派成员查询测试', true, '查询成功');
                        } else {
                            console.log('❌ 帮派成员查询失败:', response.msg || '未知错误');
                            this.addTestResult('帮派成员查询测试', false, response.msg || '查询失败');
                        }
                    } else {
                        console.log('⚠️ 响应格式不符合预期');
                        this.addTestResult('帮派成员查询测试', false, '响应格式错误');
                    }
                    resolve();
                } catch (error) {
                    console.log('❌ 响应解析失败:', error.message);
                    this.addTestResult('帮派成员查询测试', false, '响应解析失败');
                    resolve();
                }
            });
        });
    }

    async testApplyToJoinFaction() {
        console.log('\n📝 步骤6: 测试申请加入帮派...');

        const applyMessage = {
            c: 1197,
            d: {
                id: 1, // 假设帮派ID为1
                type: 1
            }
        };

        console.log('📤 发送请求:', JSON.stringify(applyMessage, null, 2));
        this.ws.send(JSON.stringify(applyMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 申请加入帮派超时');
                this.addTestResult('申请加入帮派测试', false, '申请超时');
                resolve();
            }, 10000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 申请响应:', JSON.stringify(response, null, 2));

                    // 验证响应格式
                    if (response.act_id === 1197) {
                        if (response.code === 0) {
                            console.log('✅ 申请加入帮派成功');
                            this.addTestResult('申请加入帮派测试', true, '申请成功');
                        } else {
                            console.log('❌ 申请加入帮派失败:', response.msg || '未知错误');
                            this.addTestResult('申请加入帮派测试', false, response.msg || '申请失败');
                        }
                    } else {
                        console.log('⚠️ 响应格式不符合预期');
                        this.addTestResult('申请加入帮派测试', false, '响应格式错误');
                    }
                    resolve();
                } catch (error) {
                    console.log('❌ 响应解析失败:', error.message);
                    this.addTestResult('申请加入帮派测试', false, '响应解析失败');
                    resolve();
                }
            });
        });
    }

    async testDisbandFaction() {
        console.log('\n💥 步骤7: 测试解散帮派...');

        const disbandMessage = {
            c: 1226
        };

        console.log('📤 发送请求:', JSON.stringify(disbandMessage, null, 2));
        this.ws.send(JSON.stringify(disbandMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 解散帮派超时');
                this.addTestResult('解散帮派测试', false, '解散超时');
                resolve();
            }, 10000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 解散响应:', JSON.stringify(response, null, 2));

                    // 验证响应格式
                    if (response.act_id === 1226) {
                        if (response.code === 0) {
                            console.log('✅ 解散帮派成功');
                            this.addTestResult('解散帮派测试', true, '解散成功');
                        } else {
                            console.log('❌ 解散帮派失败:', response.msg || '未知错误');
                            this.addTestResult('解散帮派测试', false, response.msg || '解散失败');
                        }
                    } else {
                        console.log('⚠️ 响应格式不符合预期');
                        this.addTestResult('解散帮派测试', false, '响应格式错误');
                    }
                    resolve();
                } catch (error) {
                    console.log('❌ 响应解析失败:', error.message);
                    this.addTestResult('解散帮派测试', false, '响应解析失败');
                    resolve();
                }
            });
        });
    }

    addTestResult(testName, success, message) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message
        });
    }

    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (result.success) successCount++;
        });

        console.log('='.repeat(50));
        console.log(`总计: ${successCount}/${totalCount} 测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！帮派系统功能正常！');
        } else {
            console.log('⚠️ 部分测试失败，请检查实现。');
        }
    }

    async disconnect() {
        console.log('\n🔌 断开连接...');
        if (this.ws) {
            this.ws.close();
            console.log('✅ 连接已断开');
        }
    }

    async runAllTests() {
        try {
            await this.connect();
            await this.login();
            await this.selectCharacter();

            // 测试帮派系统功能
            await this.testCreateFaction();
            await this.testFactionInfoQuery();
            await this.testFactionMembersQuery();
            await this.testApplyToJoinFaction();
            await this.testDisbandFaction();

            this.printTestResults();

        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
        } finally {
            await this.disconnect();
        }
    }
}

// 运行测试
if (require.main === module) {
    const tester = new FactionSystemTester();
    tester.runAllTests().catch(console.error);
}

module.exports = FactionSystemTester;
